package com.situ.stmall.manager.controller.api;

import com.github.pagehelper.PageInfo;
import com.situ.stmall.manager.entity.Category;
import com.situ.stmall.manager.entity.Result;
import com.situ.stmall.manager.service.CategoryService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
/**
 * 相当于Controller与ResponseBody结合体
 * 1.将当前类放到Spring的bean容器中
 * 2.所有处理方法，返回JSON格式
 */
@RequestMapping("/api/category")
public class APICategoryController {
    //自动注入Service层对象
    @Resource
    private CategoryService categoryService;
    /**
     * 添加,使用post
     */

    @PostMapping
    public Result add(@RequestBody Category category) {
        try {
            int code = categoryService.add(category);
            //添加成功
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            //添加失败
            return Result.error(e.getMessage());
        }
    }
    /**
     * 删除，delete
     */
    @DeleteMapping
    public Result remove(Integer id){
        try {
            int code = categoryService.remove(id);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
    /**
     * 修改
     */
    @PutMapping
    public Result edit(@RequestBody Category category){
        try {
            int code = categoryService.edit(category);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
    @GetMapping
    public Result get(Integer page, Integer limit, Category category){
        if(page == null){
            List<Category> list = categoryService.search(category);
            return Result.success(list);
        }else{
            PageInfo pageInfo = categoryService.searchByPage(page,limit,category);
            return Result.success(pageInfo);
        }

    }
    /**
     * 根据id查询
     * 通过路径传递参数id，放在URL上的参数
     */
    @GetMapping("/{id}")
    public Result get(@PathVariable("id") Integer id){
        Category category = categoryService.getById(id);
        if(category == null){
            return  Result.error("ID不存在");
        }else {
            return Result.success(category);
        }
    }
}
